package com.yunhe.commons.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

public class ImageBinaryUtils {
    private static BASE64Encoder encoder = new BASE64Encoder();
    private static BASE64Decoder decoder = new BASE64Decoder();


    /**
     * 将图片转成base64编码
     * @return
     */
    public static String getImageBinary(byte[] bytes){
        try {
            return encoder.encodeBuffer(bytes).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 将base64的编码转成图片
     * @return
     */
    public static String base64StringToImage(String base64String){
        String returnStr="";
        try {
            File fileUrl = new File("C://tempElink");
            if(!fileUrl.exists()){
                fileUrl.mkdir();    //按照时间创建文件夹
            }
            String args[]=base64String.split("data:;base64,");
            if(args.length>1){
                for(int i=1;i<args.length;i++){
                    byte[] bytes = decoder.decodeBuffer(args[i]);
                    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                    BufferedImage bi1 = ImageIO.read(bais);
                    String tempStr="C://tempElink//"+i+".png";
                    File w2 = new File(tempStr);//可以是jpg,png,gif格式
                    ImageIO.write(bi1, "jpg", w2);//不管输出什么格式图片，此处不需改动
                    returnStr+=tempStr+",";
                }
                return returnStr.substring(0,returnStr.length()-1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnStr;
    }

}